#include "v8.h"
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

v8::Handle<v8::Value> Print(const v8::Arguments& args);


//using namespace v8;

// Extracts a C string from a V8 Utf8Value.
const char* ToCString(const v8::String::Utf8Value& value) {
  return *value ? *value : "<string conversion failed>";
}


void ReportException(v8::TryCatch* try_catch) {
  v8::HandleScope handle_scope;
  v8::String::Utf8Value exception(try_catch->Exception());
  const char* exception_string = ToCString(exception);
  v8::Handle<v8::Message> message = try_catch->Message();
  if (message.IsEmpty()) {
    // V8 didn't provide any extra information about this error; just
    // print the exception.
    printf("%s\n", exception_string);
  } else {
    // Print (filename):(line number): (message).
    v8::String::Utf8Value filename(message->GetScriptResourceName());
    const char* filename_string = ToCString(filename);
    int linenum = message->GetLineNumber();
    printf("%s:%i: %s\n", filename_string, linenum, exception_string);
    // Print line of source code.
    v8::String::Utf8Value sourceline(message->GetSourceLine());
    const char* sourceline_string = ToCString(sourceline);
    printf("%s\n", sourceline_string);
    // Print wavy underline (GetUnderline is deprecated).
    int start = message->GetStartColumn();
    for (int i = 0; i < start; i++) {
      printf(" ");
    }
    int end = message->GetEndColumn();
    for (int i = start; i < end; i++) {
      printf("^");
    }
    printf("\n");
    v8::String::Utf8Value stack_trace(try_catch->StackTrace());
    if (stack_trace.length() > 0) {
      const char* stack_trace_string = ToCString(stack_trace);
      printf("%s\n", stack_trace_string);
    }
  }
}


// Executes a string within the current v8 context.
bool ExecuteString(v8::Handle<v8::String> source,
                   v8::Handle<v8::Value> name,
                   bool print_result,
                   bool report_exceptions) {
  v8::HandleScope handle_scope;
  v8::TryCatch try_catch;
  v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
  if (script.IsEmpty()) {
    // Print errors that happened during compilation.
    if (report_exceptions)
      ReportException(&try_catch);
    return false;
  } else {
    v8::Handle<v8::Value> result = script->Run();
    if (result.IsEmpty()) {
      // Print errors that happened during execution.
      if (report_exceptions)
        ReportException(&try_catch);
      return false;
    } else {
      if (print_result && !result->IsUndefined()) {
        // If all went well and the result wasn't undefined then print
        // the returned value.
        v8::String::Utf8Value str(result);
        const char* cstr = ToCString(str);
        printf("%s\n", cstr);
      }
      return true;
    }
  }
}





int main(int argc, char* argv[]) {
	v8::HandleScope handle_scope;
	v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
	global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print));
	
	v8::Persistent<v8::Context> context = v8::Context::New(NULL, global);

	
	v8::Context::Scope context_scope(context);

	// Create a string containing the JavaScript source code.
	//String source = String::New("'Hello' + ', World'");
	//Handle<String> source = String::New("'Hello' + ', World'");

	//v8::Handle<v8::String> source = v8::String::New("print(33);55");
	//ExecuteString(source, v8::String::New("unnamed"), false, true);


	v8::Handle<v8::String> source = v8::String::New("\
x = 0; i = 0; \
(function() {\
	var t0 = +new Date;\
	for (i = 0; i < 10000000; ++i)\
		x = (x + i) % 987;\
	print('x=' + x);\
	var t = (+new Date) - t0;\
	print('Execution time: ' + t + ' ms.');\
})();\
	");

	ExecuteString(source, v8::String::New("unnamed"), false, true);


	// Compile the source code.
	//Handle<Script> script = Script::Compile(source, String::New("unnamed")); 
	// Run the script to get the result.
	//Handle<Value> result = script->Run();
	// Convert the result to an ASCII string and print it.
	//String::AsciiValue ascii(result);
	//printf("%s\n", *ascii);

	//context.Dispose();
	return 0;
}



// The callback that is invoked by v8 whenever the JavaScript 'print'
// function is called.  Prints its arguments on stdout separated by
// spaces and ending with a newline.
v8::Handle<v8::Value> Print(const v8::Arguments& args) {
  bool first = true;
  for (int i = 0; i < args.Length(); i++) {
    v8::HandleScope handle_scope;
    if (first) {
      first = false;
    } else {
      printf(" ");
    }
    v8::String::Utf8Value str(args[i]);
    const char* cstr = ToCString(str);
    printf("%s", cstr);
  }
  printf("\n");
  fflush(stdout);
  return v8::Undefined();
}

